package com.example.itcacp.controller;

import com.example.itcacp.dto.response.Result;
import com.example.itcacp.dto.response.ResponseResult;
import com.example.itcacp.entity.Content;
import com.example.itcacp.entity.Project;
import com.example.itcacp.entity.User;
import com.example.itcacp.repository.mybatis.UserMapper;
import com.example.itcacp.service.*;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 通用web接口
 * */

@RestController
@RequestMapping("/api")
public class WebController {

    private static final Logger logger = LoggerFactory.getLogger(WebController.class);
    @Resource //根据对象名称自动注入依赖对象
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ContentService contentService;


    @Resource
    private DataPreparationService dataPreparationService;

    @Resource
    private ProjectRecommendationService projectRecommendationService;
    /**
     * 更新用户资料
     */
    @RequestMapping("/updateprofile")
    public Result updateprofile (@RequestBody User user) {
        userService.updateprofile ( user );
        return Result.success ();
    }

    /**
     * 上传用户头像
     * */
    @PostMapping("/{user_id}/upload-profile-photo")
    public Result uploadProfilePhoto(@PathVariable String user_id, @RequestParam("file") MultipartFile file) {
        try {
            User newdbuser = userService.uploadProfilePhoto ( user_id, file );
            return Result.success (newdbuser);
        } catch (IOException e) {
            return Result.error ( "头像上传失败！" );
        }
    }

    /**
     * 修改密码
     */
    @RequestMapping("/updatepassword")
    public Result updatepassword (@RequestBody String password,
                                  @RequestParam Long user_id) {
        userMapper.updatepassword ( password, user_id );
        return Result.success ();
    }


    /**
     * 图片上传至缓存
     * */
    @RequestMapping("/uploadImage")
    public ResponseResult<ResponseResult.ImageUploadData> uploadImage (@RequestParam("file") MultipartFile file ) {
        logger.info("接收到文件上传请求，文件名: {}", file.getOriginalFilename());
        try {
            if (file.isEmpty()) {
                return ResponseResult.imageUploadFail("上传的文件为空");
            }
            String fileUrl = contentService.uploadImage ( file );
            logger.info("文件上传成功");
            return ResponseResult.imageUploadSuccess(fileUrl, null, null);
        } catch (IOException e) {
            logger.error("文件上传失败", e);
            return ResponseResult.imageUploadFail ( "图片上传失败！" );
        }
    }

    /**
     * 主页内容推荐接口：前端通过响应数据进行区分
     * */
    @GetMapping("/contentRecommend")
    public Result contentRecommend (@RequestParam(required = false) Long userId) {
        // 构建用户 - 内容矩阵
        Map<Long, Map<Long, Integer>> userItemMatrix = dataPreparationService.buildUserItemMatrix();
        // 生成推荐列表
        RecommendationGenerator recommendationGenerator = new RecommendationGenerator ();
        int k = 5;    // 最相似的用户数量
        List<Long> recommendations = recommendationGenerator.generateRecommendations(userItemMatrix, userId, k);
        // 用内容ID查询出对应的具体内容
        List<Content> contentList = contentService.selectContentByIds ( recommendations );
        return Result.success (contentList);
    }

    /**
     * 获取基于浏览记录的项目推荐
     */
    @GetMapping("/projectRecommend")
    public Result getRecommendations(
            @RequestParam(required = false) Long userId,
            @RequestParam(defaultValue = "5") int k,
            @RequestParam(defaultValue = "10") int limit
    ) {
        List<Project> recommendations = projectRecommendationService.generateProjectRecommendations(userId, k, limit);
        return Result.success(recommendations);
    }
}
